﻿using System;
using System.Linq;
using System.Text;
using System.Windows;

namespace Kurax.BoardGames.Client.Engine {
    public class User {
        private string id, email, emailHash;

        public bool IsAuthenticated {
            get {
                return !string.IsNullOrWhiteSpace(this.Id) && !string.IsNullOrWhiteSpace(this.Email);
            }
        }

        public string Id {
            get {
                if(string.IsNullOrWhiteSpace(this.id))
                    this.LoadAuthData();
                return this.id;
            }
        }

        public string Email {
            get {
                if(string.IsNullOrWhiteSpace(this.email))
                    this.LoadAuthData();
                return this.email;
            }
        }

        public string EmailHash {
            get {
                if(this.Email == null)
                    return null;
                if(this.emailHash == null) {
                    var hashedData = (new MD5Managed()).ComputeHash(Encoding.UTF8.GetBytes(this.Email.ToLower()));
                    this.emailHash = string.Concat(hashedData.Select(b => b.ToString("x2")));
                }
                return this.emailHash;
            }
        }

        private void LoadAuthData() {
            this.id = this.email = null;
            if(!Application.Current.Host.InitParams.ContainsKey("auth"))
                return;

            var auth = Application.Current.Host.InitParams["auth"];
            if(string.IsNullOrWhiteSpace(auth))
                return;

            var authData = auth.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            if(authData.Length != 2)
                return;
            try {
                var array = Encoding.UTF8.GetBytes(authData[0]);
                Array.Reverse(array);
                var key = (new MD5Managed()).ComputeHash(array);
                var stringData = (new Crypto()).Decrypt(Convert.FromBase64String(authData[1]), key);
                this.id = Encoding.UTF8.GetString(stringData, 0, stringData.Length);
                this.email = authData[0];
            } catch {
                this.id = this.email = null;
            }
        }

        internal User() {
            //
        }

        public Uri GetGravatarUri(int size = 100) {
            return new Uri(string.Format("http://www.gravatar.com/avatar/{0}?s={1}&d=wavatar", this.EmailHash, size), UriKind.Absolute);
        }
    }
}
